const {
    DayPlan
} = require('../../../model/plan/dayPlan');

function getdate(times) {
    var now = new Date(times)
    let y = now.getFullYear()
    let m = now.getMonth() + 1
    let d = now.getDate()
    return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}


module.exports = async (req, res) => {
    // 获取post参数
    let pageSize = req.fields.pageSize
    let currentPage = req.fields.current

    let data = []
    if (!req.fields.data) {
        data = await DayPlan.find().sort('-createTime').skip((currentPage - 1) * pageSize).limit(pageSize);
    } else {
        let { username, phone, planName, planType, startTime, endTime, createTime, achieveStatus } = req.fields.data
        // 一天的毫秒数
        let MillisecondsADay = 24 * 60 * 60 * 1000;
        data = await DayPlan.find({
            'username': new RegExp(username, 'i'),
            'phone': new RegExp(phone, 'i'),
            'planName': new RegExp(planName, 'i'),
            "planType.id": planType || new RegExp(),
            'startTime': {
                $gte: startTime ? parseInt(new Date(startTime).getTime()) : 0,  //大于等于
            },
            'endTime': {
                $lte: endTime ? parseInt(new Date(endTime).getTime()) : Infinity,
            },
            'createTime': {
                $lte: createTime ? parseInt(new Date(createTime).getTime()) : Infinity,
                $gt: createTime ? parseInt(new Date(createTime).getTime() - MillisecondsADay) : 0,
            },
            'achieveStatus': achieveStatus || { $in: [0, 1, 2, 3] }
        }).sort('-createTime').skip((currentPage - 1) * pageSize).limit(pageSize);
    }

    let totalCount = data.length
    let list = data.map((item) => {
        return {
            id: item.id,
            username: item.username,
            phone: item.phone,
            planName: item.planName,
            planType: item.planType,
            startTime: getdate(item.startTime),
            endTime: getdate(item.endTime),
            achieveStatus: item.achieveStatus,
            createTime: getdate(item.createTime),
            notes: item.notes,
        }
    })
    res.send({
        code: 0,
        data: {
            data: list,
            totalCount
        }
    });
}